package restaurant.behaviours.booking;

import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import restaurant.agents.BookingAgent;
import restaurant.core.CustomizedPerformative;

/**
 * BookingAgent behaviour which performs the action to answer to a booking request
 * @author Domenico Ventura
 *
 */
public class BookingRequestBehaviour extends CyclicBehaviour {
	private static final long serialVersionUID = -6788001641734043714L;
	private BookingAgent agent;
	
	public BookingRequestBehaviour(BookingAgent agent) {
		super(agent);
		this.agent = agent;
	}

	@Override
	public void action() {
		MessageTemplate messageTemplate = MessageTemplate.MatchPerformative(CustomizedPerformative.BOOKING);
		ACLMessage message = myAgent.receive(messageTemplate);
		if(message != null) {
			System.out.println("BookingAgent: Salve " + message.getSender().getLocalName() + " controllo che ci sia un tavolo disponibile");
			
			ACLMessage answer = message.createReply();
			
			// Searching free table
			if(this.agent.restaurant.tables != null) {
				for(int i = 0; i < this.agent.restaurant.tables.size(); i++) {
					if(this.agent.restaurant.tables.get(i).isFree()) {
						answer.setContent(String.valueOf(i));
					
						System.out.println("BookingAgent: Tavolo disponibile n. " + i + " pos: " + this.agent.restaurant.tables.get(i));
					
						myAgent.send(answer);
						return;
					}
				}
			}
			
			System.out.println("BookingAgent: Nessun tavolo disponibile");
			
			answer.setContent("not-available");
			myAgent.send(answer);
		}
	}
}